package com.gohi.main.wxapi.process;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.gohi.main.wxapi.action.WxpiAction;
import com.gohi.main.wxapi.vo.Article;
import com.gohi.main.wxapi.vo.MsgRequest;
import com.gohi.main.wxapi.vo.MsgResponseImage;
import com.gohi.main.wxapi.vo.MsgResponseMusic;
import com.gohi.main.wxapi.vo.MsgResponseNews;
import com.gohi.main.wxapi.vo.MsgResponseText;
import com.gohi.main.wxapi.vo.MsgResponseVideo;
import com.gohi.main.wxapi.vo.MsgResponseVoice;
import com.gohi.main.wxapi.vo.Template;

/**
 * xml 消息处理工具类
 * 
 * @author brain
 */

public class MsgXmlUtil {
	// public static Logger logger = Logger.getLogger(MsgXmlUtil.class);
	// 将request 消息 转换成 请求消息对象
	public static MsgRequest parseXml(HttpServletRequest request) {
		MsgRequest msgReq = new MsgRequest();

		// 解析XML
		InputStream inputStream = null;
		Document document = null;
		try {
			inputStream = request.getInputStream();
			SAXReader reader = new SAXReader();
			// logger.info("")
			// System.err.println(inputStream.toString());
			document = reader.read(inputStream);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			// e1.printStackTrace();
		} catch (DocumentException e) {
			System.err.println(inputStream);
			// TODO Auto-generated catch block
			// e.printStackTrace();
			return null;
		}

		Element root = document.getRootElement();
		List<Element> elementList = root.elements();
		msgReq.setUuid(request.getParameter("id"));// 获取到微信传来的参数
		// 遍历节点，封装成对象
		for (Element e : elementList) {
			String name = e.getName();
			String text = e.getText();

			if ("MsgType".equals(name)) {
				msgReq.setMsgType(text);
			} else if ("MsgId".equals(name)) {
				msgReq.setMsgId(text);
			} else if ("MsgId".equals(name)) {
				msgReq.setMsgId(text);
			} else if ("FromUserName".equals(name)) {
				msgReq.setFromUserName(text);
			} else if ("ToUserName".equals(name)) {
				msgReq.setToUserName(text);
			} else if ("CreateTime".equals(name)) {
				msgReq.setCreateTime(text);

			} else if ("Content".equals(name)) {// 文本消息
				msgReq.setContent(text);
			} else if ("PicUrl".equals(name)) {// 图片消息
				msgReq.setPicUrl(text);
			} else if ("Location_X".equals(name)) {// 地理位置消息
				msgReq.setLocation_X(text);
			} else if ("Location_Y".equals(name)) {
				msgReq.setLocation_Y(text);
			} else if ("Scale".equals(name)) {
				msgReq.setScale(text);
			} else if ("Label".equals(name)) {
				msgReq.setLabel(text);
			} else if ("Event".equals(name)) {// 事件消息
				msgReq.setEvent(text);
			} else if ("EventKey".equals(name)) {
				msgReq.setEventKey(text);
			}
		}

		try {
			inputStream.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		inputStream = null;
		return msgReq;
	}

	public static String textToXml(MsgResponseText text) {
		xstream.alias("xml", text.getClass());
		return xstream.toXML(text);
	}

	public static String imageToXml(MsgResponseImage image) {
		xstream.alias("xml", image.getClass());
		return xstream.toXML(image);
	}

	public static String voiceToXml(MsgResponseVoice voice) {
		xstream.alias("xml", voice.getClass());
		return xstream.toXML(voice);
	}

	public static String videoToXml(MsgResponseVideo video) {
		xstream.alias("xml", video.getClass());
		return xstream.toXML(video);
	}

	public static String musicToXml(MsgResponseMusic music) {
		xstream.alias("xml", music.getClass());
		return xstream.toXML(music);
	}

	public static String newsToXml(MsgResponseNews news) {
		xstream.alias("xml", news.getClass());
		xstream.alias("item", new Article().getClass());
		return xstream.toXML(news);
	}

	/**
	 * 扩展xstream，让xml节点增加CDATA标记
	 */
	public static XStream xstream = new XStream(new XppDriver() {
		public HierarchicalStreamWriter createWriter(Writer out) {
			return new PrettyPrintWriter(out) {
				boolean CDATA = true;

				@SuppressWarnings("unchecked")
				public void startNode(String name, Class clazz) {
					super.startNode(name, clazz);
				}

				protected void writeText(QuickWriter writer, String text) {
					if (CDATA) {
						writer.write("<![CDATA[");
						writer.write(text);
						writer.write("]]>");
					} else {
						writer.write(text);
					}
				}
			};
		}
	});

	public static void main(String[] args) {

		String xml = "<xml><ToUserName><![CDATA[gh_02606721ab8e]]></ToUserName>"
				+ "<FromUserName><![CDATA[oUig6t-5P5rZuWQZpp6SRO7odoDg]]></FromUserName>"
				+ "<CreateTime>1407424506</CreateTime>"
				+ "<MsgType><![CDATA[text]]></MsgType>"
				+ "<Content><![CDATA[1]]></Content>"
				+ "<MsgId>6044842225059613150</MsgId>" + "</xml>";

		InputStream in_nocode = new ByteArrayInputStream(xml.getBytes());

		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(in_nocode);
			Element root = document.getRootElement();
			List<Element> elementList = root.elements();

			MsgRequest msgReq = new MsgRequest();

			// 遍历节点，封装成对象
			for (Element e : elementList) {
				String name = e.getName();
				String text = e.getText();
				String msgtype = null;

				if ("MsgType".equals(name)) {
					msgReq.setMsgType(text);
				} else if ("MsgId".equals(name)) {
					msgReq.setMsgId(text);
				} else if ("MsgId".equals(name)) {
					msgReq.setMsgId(text);
				} else if ("FromUserName".equals(name)) {
					msgReq.setFromUserName(text);
				} else if ("ToUserName".equals(name)) {
					msgReq.setToUserName(text);
				} else if ("CreateTime".equals(name)) {
					msgReq.setCreateTime(text);

				} else if ("Content".equals(name)) {// 文本消息
					msgReq.setContent(text);
				} else if ("PicUrl".equals(name)) {// 图片消息
					msgReq.setPicUrl(text);
				} else if ("Location_X".equals(name)) {// 地理位置消息
					msgReq.setLocation_X(text);
				} else if ("Location_Y".equals(name)) {
					msgReq.setLocation_Y(text);
				} else if ("Scale".equals(name)) {
					msgReq.setScale(text);
				} else if ("Label".equals(name)) {
					msgReq.setLabel(text);
				} else if ("Event".equals(name)) {// 事件消息
					msgReq.setEvent(text);
				} else if ("EventKey".equals(name)) {
					msgReq.setEventKey(text);
				}
			}

			System.out.println(msgReq.getFromUserName());
		} catch (Exception e1) {
			e1.printStackTrace();
		}

	}

	/**
	 * 发送模板消息
	 * 
	 * @param template
	 *            模板数据
	 * @param token
	 *            值
	 * @return
	 */
	public static String sendTemplateMsg(Template template, String token) {
		String s = JSONObject.fromObject(template).toString();
		String url = WxApi.getTemplate(token);
		JSONObject jsonObject = WxApi.httpsRequest(url, "POST", s);
		return jsonObject.toString();
	}
}
